// pages/cashier_table/cashier_table.js
let listBehavior = require('../../behavior/list')


let assistAcctObj = {}          // 辅助核算列表

let { formatDate, getMonthFirstDate, getMonthLastDate, } = wx.$util,
    first = formatDate(getMonthFirstDate(), 'yyyy-MM-dd'),
    last = formatDate(getMonthLastDate(), 'yyyy-MM-dd')

let baseQuery = { CompareValue: '0', CompareWith: 'row_id', Operator: '<>', or: 0, }, // 221101 过滤初始项，初始项目不显示，但好像不管用
    baseSearchWhere = [
      { CompareValue: first, CompareWith: 'date', Operator: '>=', or: 0, },
      { CompareValue: last, CompareWith: 'date', Operator: '<=', or: 0, },
    ],
    searchWhere = [],
    children = []

Page({
  behaviors: [ listBehavior, ],
  /**
   * 页面的初始数据
   */
  data: {
    auth: {},
    // list: [],                     // 出纳表列表
    limit: 20,
    // total: '',                    // 总记录数
    incomeTotal: '0.00',          // 总收入
    payTotal: '0.00',             // 总支出

    // 筛选条件
    keyList: [
      { field_id: 'mark', field_name: '摘要', },
      { field_id: 'debit_amount', field_name: '金额', },
      { field_id: 'credit_amount', field_name: '', },
      { field_id: 'balance', field_name: '余额', },
    ],
    searchList: [
      { field_name: '账号', type: 'reference1', field_id: 'account_id', optionList: [], optionId: 'number', optionName: 'account_shortname', },
      { field_name: '收入类型', type: 'picklist', field_id: 'debit_amount', optionList: [
        { id: 'debit_amount', label: '收入', },
        { id: 'credit_amount', label: '支出', },
      ], optionId: 'id', },
      { field_name: '科目名称', type: 'reference1', field_id: 'target_account_id', optionList: [], optionId: 'id', },
      { field_name: '发生日期', type: 'date', field_id: 'date', start: first, end: last, },
    ],
  },

  navTo(e) {
    let url = e.currentTarget.dataset.url,
        { auth, } = this.data,
        msg = ''
    if(!url) return
    // if(url.indexOf('all_cashier') > -1 && !auth.tableAppend) msg = '抱歉，您没有权限新增该模块数据'
    if(msg) {
      wx.$toast(msg)
      return
    }
    wx.navigateTo({
      url,
    })
  },

  // 搜索栏
  searchVal(e) {
    children = []
    let arr = e.detail
    arr.forEach(item => {
      if(item.CompareValue) {
        if(item.CompareWith === 'mark') {
          children.push(item)
        } else if(!isNaN(item.CompareValue)) {
          item.Operator = '='
          children.push(item)
        }
      }
    })
    // children.forEach(item => {
    //   if(item.CompareWith !== 'mark') item.Operator = '='
    // })

    this.getFirstPage()
  },
  // 快速查询
  searchQuick(e) {
    searchWhere = e.detail
    searchWhere.forEach(item => {
      if(item.CompareValue === 'debit_amount') {
        item.CompareWith = item.CompareValue
        item.CompareValue = 0
        item.Operator = '>'
      }
    })
    searchWhere.push(baseQuery)
    this.getFirstPage()
  },

  // 凭证按钮
  viewVoucher(e) {
    let { item, } = e.currentTarget.dataset,
        { row_id, account_period, table_id, table_id_row_id, voucher_id, debit_amount, credit_amount, is_charges, } = item,
        url = `../accounting_voucher_detl/accounting_voucher_detl?id=${row_id}&period=${account_period}&table_id=${table_id || 'all_cashier'}&table_id_row_id=${table_id_row_id || row_id}&voucher_id=${voucher_id}&price=${debit_amount || credit_amount}&canedit=${is_charges ? 0 : 1}`
    wx.navigateTo({
      url,
    })
  },
  // 插入
  onInsert(e) {
    let { item, } = e.currentTarget.dataset
    wx.navigateTo({
      url: `../cashier_table_add/cashier_table_add?entity=all_cashier&sort=${Number(item.sort) + 1}`,
    })
  },
  // 查看
  onDetl(e) {
    let { limit, } = this.data,
        { item, i, } = e.currentTarget.dataset,
        { row_id, } = item
    wx.navigateTo({
      url: `../cashier_table_add/cashier_table_add?entity=all_cashier&status=edit&rid=${row_id}`,
    })
  },
  // 删除
  onDel(e) {
    let { auth, limit, } = this.data,
        { item, i, } = e.currentTarget.dataset,
        { row_id, } = item
    if(!auth.tableDelete) {
      wx.$toast('抱歉，您没有权限删除该模块数据')
      return
    }
    wx.showModal({
      title: '提示',
      content: '确认删除该记录？',
      success: (res) => {
        if(res.confirm) this.delData(row_id)
      },
    })
  },
  // 刷新编辑/删除 成功后的数据
  refreshData() {
    this.data.list = []
    this.getDataList(1)
  },

  // 接口
  ready() {
    // 获取账号、科目名称 选项列表
    let p0 = this.getOptionList(0, 'account_id', 3, 'DynamicQuery/query_dynamic', { limit: 0, oby: 'account_id', page: 0, table_id: 'all_cashier_account', }),
        p1 = this.getOptionList(1, 'target_account_id', 3, 'Account/select_account')

    Promise.all([p0, p1]).then(res => {
      let searchList = this.data.searchList,
          obj = {}
      res.forEach((item, i) => {
        obj = { ...obj, ...item, }
      })
      searchList.forEach(item => {
        let key = item.field_id
        if(obj[key]) item.optionList = obj[key]
      })
      this.setData({
        searchList,
      })
    })
  },
  getOptionList() {
    return new Promise((resolve, reject) => {
      let [ method, key, v, url, params, ] = arguments
      let request = method ? wx.$get : wx.$post
      request(v, url, params).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        rows = rows.flat()
        resolve({ [key]: rows, })
      })
    })
  },
  // 获取出纳列表
  getDataList(thisPage) {
    if(!this.data.auth.tableSee) {
      wx.$toast('抱歉，您没有权限查看该模块')
      this.setData({
        total: 0,
        page,
        limit,
      })
      return
    }

    let { page, limit, list, } = this.data,
        post = {
          oby: 'sort',
          page: thisPage || page,
          limit,
          // SearchWhere: {
          //   type: 'and',
          //   filters: searchWhere,
          //   children: [],
          // },
        }
    if(searchWhere.length) {
      post.SearchWhere = {
        type: 'and',
        filters: searchWhere,
        children: [],
      }
      if(children.length) {
        post.SearchWhere.children.push({
          type: 'and',
          filters: children,
        })
      }
    }

    wx.$post(3, 'Cashier/query_all_cashier', post).then(res => {
      if(res.errcode !== 0) return
      let rows = res.data.row,
          total = res.data.total,
          incomeTotal = 0,
          payTotal = 0,
          filterRows = rows.filter(row => row.row_id !== 0) // 221101 初始项不显示
      if(rows.length !== filterRows.length) {
        total = total - (rows.length - filterRows.length)
        rows = filterRows
      }
      rows.forEach((item, i) => {
        let { credit_amount, debit_amount, balance, date, assist_account_json, is_assist_account, debit_amount_totle, credit_amount_totle, } = item
        if(!i) {
          incomeTotal = debit_amount_totle
          payTotal = credit_amount_totle
        }
        if(item.date) item.date = date.split(' ')[0]
        // 支出
        if(credit_amount) item.credit_amount = wx.$util.formatNum(credit_amount)
        // 收入
        if(debit_amount) item.debit_amount = wx.$util.formatNum(debit_amount)
        item.balance = wx.$util.formatNum(balance)

        // 辅助核算json 字符串
        let json = '',
            keys = [],
            values = []
        if(is_assist_account) {
          try {
            json = JSON.parse(assist_account_json)
          } catch(error) {}
        }
        if(json) {
          let types = json.type.split(','),
              ids = json.id.split(','),
              names = json.name.split(',')
          types.forEach((rowid, i) => {
            let id = ids[i] + ' ',
                name = names[i]
            keys.push(assistAcctObj[rowid])
            values.push(name.replace(id, ''))
          })
        }
        item.assistAcctKeys = keys
        item.assistAcctVals = values
      })
      if(thisPage) {
        this.data.list = [ ...list, ...rows, ]
        if(thisPage === page || thisPage * limit >= total) {
          this.setData({
            list: this.data.list,
            incomeTotal: wx.$util.formatNum(incomeTotal),
            payTotal: wx.$util.formatNum(payTotal),
            total,
            page: thisPage,
          })
        } else {
          this.getDataList(++thisPage)
        }
      } else {
        if(page !== 1) rows = [ ...list, ...rows, ]
        this.setData({
          list: rows,
          incomeTotal: wx.$util.formatNum(incomeTotal),
          payTotal: wx.$util.formatNum(payTotal),
          total,
          page,
        })
      }
    })
  },
  // 获取辅佐核算设置列表
  getAssistAcctList() {
    // return
    return new Promise((resolve, reject) => {
      wx.$post(1, 'AllAssistAccount/select_all_assist_account', {}).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row,
            obj = {}
        rows.forEach(item => {
          obj[item.row_id] = item.assist_account
        })
        assistAcctObj = obj
        resolve()
      })
    })
  },
  // 删除数据
  delData(rowId) {
    wx.showLoading({ mask: true, })
    wx.$post(3, 'Cashier/del_all_cashier', { row_id: rowId, }).then(res => {
      if(res.errcode !== 0) return
      wx.$toast('删除成功')
      this.refreshData()
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    let { entity, } = options,
        auth = await wx.$getAuth(entity)
    this.data.auth = auth
    searchWhere = [ ...baseSearchWhere, ]
    if(!auth.tableSee) {
      wx.$toast('抱歉，您没有权限查看该模块', 2000).then(() => {
        wx.navigateBack({ delta: 1, })
      })
      return
    }
    this.ready()
    await this.getAssistAcctList()
    this.getDataList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
